package com.example.demo.grbkxt.servlet;

import com.example.demo.grbkxt.mapper.BlogMapper;
import com.example.demo.grbkxt.mapper.CommentMapper;
import com.example.demo.grbkxt.model.Blog;
import com.example.demo.grbkxt.model.Comment;
import com.example.demo.grbkxt.model.User;
import com.example.demo.grbkxt.util.MyBatisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "blogServlet", urlPatterns = { "/blog/*" })
public class BlogServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        User user = (User) request.getSession().getAttribute("user");

        try (SqlSession sqlSession = MyBatisUtil.openSession()) {
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

            if ("/view".equals(pathInfo)) {
                String id = request.getParameter("id");
                System.out.println("Viewing blog with ID: " + id);

                Blog blog = mapper.getBlogById(id);
                if (blog != null) {
                    System.out.println("Found blog: " + blog.getTitle());
                    CommentMapper commentMapper = sqlSession.getMapper(CommentMapper.class);
                    List<Comment> comments = commentMapper.getCommentsByBlogId(id);
                    System.out.println("Found comments: " + (comments != null ? comments.size() : 0));

                    request.setAttribute("blog", blog);
                    request.setAttribute("comments", comments != null ? comments : new ArrayList<>());
                    request.getRequestDispatcher("/WEB-INF/views/blog/detail.jsp").forward(request, response);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "博客不存在");
                }
                return;
            } else if ("/admin".equals(pathInfo) && user.isAdmin()) {
                // 管理员页面
                List<Blog> blogs = mapper.getAllBlogs();
                request.setAttribute("blogs", blogs);
                request.getRequestDispatcher("/WEB-INF/views/admin/dashboard.jsp").forward(request, response);
            } else if ("/edit".equals(pathInfo) && user.isAdmin()) {
                String id = request.getParameter("id");
                Blog blog = mapper.getBlogById(id);
                if (blog != null) {
                    System.out.println("Editing blog with category: " + blog.getCategory());
                    request.setAttribute("blog", blog);
                    request.getRequestDispatcher("/WEB-INF/views/admin/edit.jsp").forward(request, response);
                }
            } else if ("/user".equals(pathInfo)) {
                // 普通用户页面
                List<Blog> blogs = mapper.getPublicBlogs();
                request.setAttribute("blogs", blogs);
                request.getRequestDispatcher("/WEB-INF/views/user/dashboard.jsp").forward(request, response);
            } else if ("/search".equals(pathInfo)) {
                // 处理搜索请求
                String keyword = request.getParameter("keyword");
                String category = request.getParameter("category");
                List<Blog> searchResults = mapper.searchBlogs(keyword, category);
                request.setAttribute("blogs", searchResults);
                request.setAttribute("keyword", keyword);
                request.setAttribute("selectedCategory", category);
                request.getRequestDispatcher("/WEB-INF/views/user/dashboard.jsp").forward(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");

        if (user != null && user.isAdmin()) {
            try (SqlSession sqlSession = MyBatisUtil.openSession()) {
                BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
                String action = request.getPathInfo();

                if (action == null || action.equals("/")) {
                    // 处理新增博客
                    String title = request.getParameter("title");
                    String content = request.getParameter("content");
                    String category = request.getParameter("category");
                    boolean adminOnly = "on".equals(request.getParameter("adminOnly"));

                    Blog blog = new Blog();
                    blog.setId(UUID.randomUUID().toString());
                    blog.setTitle(title);
                    blog.setContent(content);
                    blog.setCategory(category);
                    blog.setCreateTime(new Date());
                    blog.setAdminOnly(adminOnly);

                    blogMapper.addBlog(blog);
                    sqlSession.commit();
                    response.sendRedirect(request.getContextPath() + "/blog/admin");
                } else if (action.equals("/update")) {
                    // 处理更新博客
                    String id = request.getParameter("id");
                    String title = request.getParameter("title");
                    String content = request.getParameter("content");
                    String category = request.getParameter("category");
                    boolean adminOnly = "on".equals(request.getParameter("adminOnly"));

                    Blog blog = new Blog();
                    blog.setId(id);
                    blog.setTitle(title);
                    blog.setContent(content);
                    blog.setCategory(category);
                    blog.setCreateTime(new Date());
                    blog.setAdminOnly(adminOnly);

                    blogMapper.updateBlog(blog);
                    sqlSession.commit();
                    response.sendRedirect(request.getContextPath() + "/blog/admin");
                }
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/blog/user");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (SqlSession session = MyBatisUtil.openSession()) {
            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            String id = request.getParameter("id");
            blogMapper.deleteBlog(id);
            session.commit();
            response.setStatus(200);
        }
    }
}
